
// ==UserScript==
// @name         csdn一键打印
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://blog.csdn.net/*/article/details/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=csdn.net
// @grant        none
// ==/UserScript==

let htmlStr = `
  <button id="do-print">
    一键打印
    <br/>
     建议A4纸缩放比例调成125%
  </button>
  <style>
    #do-print{
      position: fixed;
      right: 20px;
      top: 80px;
    }
  </style>
`



let domDiv = document.createElement('div')

function initDom(){
  domDiv.innerHTML = htmlStr
  document.querySelector('body').append(domDiv)
}


// 删除多余的元素，保留要打印的部分
function doFilter(selectorStr){
    if(typeof selectorStr != 'string'){
      return
    }
    let content = document.querySelector(selectorStr)
    let body = document.querySelector('body')
    let child = content
    let parent = content.parentNode
    while(child != body){
      console.log(parent)
      for(let c of parent.childNodes){
        if(c != child){
          if(c.style){
            c.style.display = 'none'
          }
          // 如果像下面这样直接删除元素，可能引起某些选择器失效
          // parent.removeChild(c)
          // console.log('rm', c)
        }
      }
      child = parent
      parent = parent.parentElement
    }

}




(function() {
    'use strict';
    initDom()
    document.querySelector('#do-print').addEventListener('click', () => {
      doFilter('#content_views')
      Object.assign(document.querySelector('main').style, { width: '800px', position:'relative', left: '100px'})
      print()
    })
})();